Page({
  data: {
    score: 0, // 当前得分
    direction: 'right', // 当前方向
    snake: [{ x: 10, y: 10 }], // 蛇的身体
    food: { x: 5, y: 5 }, // 食物的位置
    gameOver: false // 游戏是否结束
  },

  onLoad() {
    this.startGame();
  },

  // 开始游戏
  startGame() {
    this.setData({
      score: 0,
      direction: 'right',
      snake: [{ x: 10, y: 10 }],
      food: this.generateFood(),
      gameOver: false
    });
    this.gameLoop();
  },

  // 游戏主循环
  gameLoop() {
    if (this.data.gameOver) return;

    const { snake, food, direction } = this.data;
    const head = { ...snake[0] };

    // 根据方向移动蛇头
    switch (direction) {
      case 'up': head.y -= 1; break;
      case 'down': head.y += 1; break;
      case 'left': head.x -= 1; break;
      case 'right': head.x += 1; break;
    }

    // 检查是否撞墙或撞到自己
    if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20 || snake.some(segment => segment.x === head.x && segment.y === head.y)) {
      this.setData({ gameOver: true });
      wx.showToast({ title: '游戏结束', icon: 'none' });
      return;
    }

    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
      this.setData({
        score: this.data.score + 1,
        food: this.generateFood()
      });
      snake.unshift(head);
    } else {
      snake.unshift(head);
      snake.pop();
    }

    this.setData({ snake });
    this.drawGame();

    // 继续游戏循环
    setTimeout(() => this.gameLoop(), 200);
  },

  // 生成食物位置
  generateFood() {
    return {
      x: Math.floor(Math.random() * 20),
      y: Math.floor(Math.random() * 20)
    };
  },

  // 绘制游戏画面
  drawGame() {
    const ctx = wx.createCanvasContext('snakeCanvas');
    const { snake, food } = this.data;

    // 清空画布
    ctx.clearRect(0, 0, 300, 300);

    // 绘制食物
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * 15, food.y * 15, 15, 15);

    // 绘制蛇
    ctx.fillStyle = 'green';
    snake.forEach(segment => {
      ctx.fillRect(segment.x * 15, segment.y * 15, 15, 15);
    });

    ctx.draw();
  },

  // 改变方向
  changeDirection(e) {
    const newDirection = e.currentTarget.dataset.direction;
    const { direction } = this.data;

    // 防止反向移动
    if (
      (direction === 'up' && newDirection === 'down') ||
      (direction === 'down' && newDirection === 'up') ||
      (direction === 'left' && newDirection === 'right') ||
      (direction === 'right' && newDirection === 'left')
    ) return;

    this.setData({ direction: newDirection });
  },

  // 重新开始游戏
  restartGame() {
    this.startGame();
  }
});